package com.bd.scm.module.login.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bd.scm.domain.dto.login.LoginDto;
import com.bd.scm.domain.dto.tree.ZTree;
import com.bd.scm.module.department.service.IDtDepService;
import com.bd.scm.module.utils.EhcacheUtil;
import com.bd.utils.ArrayUtils;
import com.bd.utils.DateUtil;
import com.bd.utils.StringUtils;
import com.bd.utils.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 控制层基类 ，所有业务类都应该继承此类
 *
 * @author chengl
 * @Date 2011-8-16
 * @version 1.0
 */
@Slf4j
public abstract class AbstractBaseController {
    /**
     * 定义常量
     */
    private static final Integer A_NUM = 3, B_NUM = 2;

    @Autowired
    IDtDepService deptService;

    protected Result resultObj = new Result();// 封装一个统一对象用于返回前台

    protected Map<String, Object> queryMap = new HashMap<String, Object>();// 用来设置给前台显示map

    protected Map<String, String> params = new HashMap<String, String>();// 用来设置给前台显示map

    private static String[] excludeSearchArr = new String[] { "page", "pageSize", "dir", "sort" };// 搜索排除值

    protected Page<?> resultPage = new Page();// 封装一个分页对象用于返回前台

    protected Map<String, String> resultMap = new HashMap<String, String>();// 用来设置给前台显示map


    /**
     * 把搜索值转为map，供后台及界面使用
     *
     * @param request
     * @return
     */
    public Map<String, Object> getSearchMap(HttpServletRequest request) {
        queryMap.clear();
        Map map = request.getParameterMap();
        for (Object key : map.keySet()) {
            String keyStr = key.toString();
            if (!"".equals(keyStr))
                if (!ArrayUtils.isInArray(excludeSearchArr, keyStr)) {
                    try {
                        this.queryMap.put(keyStr, java.net.URLDecoder.decode(request.getParameter(key.toString()), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
        }
        return this.queryMap;
    }
    /**
     * 登录
     *
     * @param request     请求器
     * @param response    响应器
     * @param loginDto    存放信息
     */
    public void setLoginInfo(HttpServletRequest request, HttpServletResponse response, LoginDto loginDto,String userSerial) {

        HttpSession session = request.getSession();
        session.setAttribute("query_startDate", DateUtil.getMonthFirstDay());
        session.setAttribute("query_endDate", DateUtil.getMonthLastDay());
        session.setAttribute("current_time", DateUtil.getCurYearMonth());
        session.setAttribute("account", String.valueOf(queryMap.get("user")));

        //获取部门
        List<LoginDto> findDept = deptService.findDept(loginDto);
        loginDto.setDepts(findDept);

        List<String> findDeptid = deptService.findDeptid(loginDto);

        List<String> initDept = new ArrayList<String>();

        session.setAttribute("findDeptid", initDept);

        //获取权限所要的父级id
        Set<String> findDepNo = new HashSet<String>();

        boolean flagDept = true;

        for (LoginDto dtDep : findDept) {
            if (dtDep.getDepNo().equals("001")) {
                flagDept = false;
                break;
            }
            gainDepNo(findDepNo,dtDep.getDepNo());
        }

        if (flagDept) {
            initDept.addAll(findDeptid);
            session.setAttribute("initDept", initDept);
            if (!StringUtils.isNullOrEmpty(findDepNo)) {
                loginDto.setDepNos(StringUtils.join(findDepNo, ","));
                findDeptid.addAll(deptService.findSoleDeptid(loginDto));
            }
            session.setAttribute("findDeptid", findDeptid);
        } else {
            session.setAttribute("initDept", initDept);
            session.setAttribute("findDeptid", initDept);
        }

        log.info("===============================设置部门缓存================================");
        List<ZTree> deptList = deptService.getZTreeList(0L, findDeptid);
        if(null!=deptList){
            EhcacheUtil.put(userSerial, JSONObject.toJSONString(deptList));
        }


        //获取场所编号
//        List<JSONObject> findPlace = deptService.findPlace(String.valueOf(queryMap.get("user")));
//        queryMap.put("places", findPlace);
//        //获取场所id
//        List<String> findPlaceid = deptService.findPlaceid(queryMap);
//        List<String> initPlace = new ArrayList<String>();
//        session.setAttribute("findPlaceid", initPlace);
//        boolean flagPlace =true;
//        //获取权限所要的父级id
//        Set<String> findPlaceDepNo = new HashSet<String>();
//
//        for (JSONObject jsonObject : findPlace) {
//            if(jsonObject.getString("depNo").equals("001")){
//                flagPlace = false;
//                break;
//            }
//            gainDepNo(findPlaceDepNo,jsonObject.getString("depNo"));
//        }
//
//        if(flagPlace){
//            initPlace.addAll(findPlaceid);
//            session.setAttribute("initPlace", initPlace);
//            if(!StringUtils.isNullOrEmpty(findPlaceDepNo)){
//                queryMap.put("depNos", StringUtils.join(findPlaceDepNo, ","));
//                findPlaceid.addAll(deptService.findSolePlaceid(queryMap));
//            }
//            session.setAttribute("findPlaceid", findPlaceid);
//        }else{
//            session.setAttribute("initPlace", initPlace);
//            session.setAttribute("findPlaceid", initPlace);
//        }
    }

    /**
     * 获取场所编号
     *
     * @param list  场所编号集合
     * @param depNo 场所编号
     * @return 场所集合
     */
    public static Set<String> gainDepNo(Set<String> list, String depNo) {
        if (depNo.length() > A_NUM) {
            list.add(depNo.substring(0, depNo.length() - B_NUM));
            gainDepNo(list, depNo.substring(0, depNo.length() - B_NUM));
        }
        return list;
    }
}
